package com.foreverwin.jzymes.framework.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.sap.me.frame.JNDIUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;

import javax.naming.NamingException;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ervin on 2018/12/23.
 */
@Configuration
public class DataSourceConfig {


    @Profile({"dev","qas","prod"})
    @Bean(name="masterDataSource")
    public DataSource prodDataSource(){
        DataSource dataSource = null;
        try {
            dataSource = (DataSource) JNDIUtils.getInitialContext().lookup("jdbc/wipPool");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Profile({"dev","qas","prod"})
    @Bean(name="slaveDataSource")
    public DataSource prodOdsDataSource(){
        DataSource dataSource = null;
        try {
            dataSource = (DataSource) JNDIUtils.getInitialContext().lookup("jdbc/odsPool");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Profile("local")
    @Bean(name="masterDataSource")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource localDataSource()
    {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

    @Profile("local")
    @Bean(name="slaveDataSource")
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource localOdsdataSource()
    {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

}
